<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
import {Material, MaterialListParam} from "@/api/material/type";
import {addApi, deleteApi, updateApi, getListApi} from "@/api/material";
// 物料分类精简类别，用于树形结构展示
import {getSimpleListApi} from "@/api/materialCategory/index.ts";
// 单位列表，用于物料单位下拉框
import {getUnitSimpleListApi} from "@/api/unit/index.ts";
// 图标组件
import {Search, Refresh, Plus, Edit, Delete, Folder, Setting, InfoFilled, ZoomIn, Picture, Document, Grid} from '@element-plus/icons-vue'
import TreeSelect from "@/components/TreeSelect/index.vue";
import {Unit} from "@/api/unit/type.ts";

// ----------------------- 组件状态定义 -----------------------
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})


// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<MaterialListParam>({
  materialCode: undefined,
  materialName: undefined,
  categoryId: undefined,
  brand: undefined,
  manufacturer: undefined,
  materialType: undefined,
  isActive: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.categoryId = currentCategoryId.value || undefined
  searchForm.brand = undefined
  searchForm.manufacturer = undefined
  searchForm.materialType = undefined
  searchForm.isActive = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 新增/编辑表单相关 -----------------------
const addFormRef = ref<FormInstance>()
const addForm = reactive<Material>({
  id: undefined,
  materialCode: undefined,  // 分类编码
  materialName: undefined,  // 分类名称
  categoryId: undefined,  // 物料类型id
  unitId: undefined,  // 单位id
  specification: undefined,  // 规格
  specificationTwo: undefined,  // 规格2
  brand: undefined,   // 品牌
  manufacturer: undefined,  // 生产厂家
  price: undefined,  // 采购价格
  purchasePrice: undefined,  // 采购单价
  materialModel: undefined,  // 物料型号
  materialType: undefined,  // 材质
  unitWeight: undefined,  // 米重(kg/m)
  unitArea: undefined,  // 米面积(m²/m)
  totalArea: undefined,  // 总面积(m²/件)
  totalWeight: undefined,  // 总重(kg/件)
  thickness: undefined, // 厚度(mm)
  length: undefined,  // 高度
  breadth: undefined, // 宽度
  imageUrl: undefined, // 初始化为undefined而不是null
  process: undefined,  // 工艺
  mileagePrice: undefined,  // 人工公里数单价
  unitPriceCoefficient: undefined,  // 单价索取系数
  materialRequisitionCoefficient: undefined,  // 材料索取系数
  isActive: 0,  // 物料是否启用，0: 启用，1: 禁用
  createTime: undefined,  // 创建时间
  updateTime: undefined,  // 更新时间
  fileList: [] // 新增文件列表
})

// 表单校验规则
const rules = {
  materialCode: [{required: true, message: '请输入物料编码', trigger: 'blur'}],
  materialName: [{required: true, message: '请输入物料名称', trigger: 'blur'}],
  categoryId: [{required: true, message: '请选择物料类型', trigger: 'change'}],
  unitId: [{required: true, message: '请选择计量单位', trigger: 'change'}]
}

// 打开新增弹框
const openAdd = () => {
  dialog.title = '新增物料'
  dialog.width = 900
  dialog.height = 400
  onShow()
}

// 打开编辑弹框
const openEdit = (row: Material) => {
  dialog.title = '编辑物料'
  dialog.width = 900
  dialog.height = 400
  nextTick(() => {
    Object.assign(addForm, row)
    // 初始化 fileList
    if (row.imageUrl) {
      addForm.fileList = [{
        name: row.imageUrl.split('/').pop(),
        url: row.imageUrl
      }]
    } else {
      addForm.fileList = []
    }
  })
  onShow()
}

// 关闭弹框
const closeDialog = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    id: undefined,
    materialCode: undefined,
    materialName: undefined,
    categoryId: undefined,
    unitId: undefined,
    specification: undefined,
    specificationTwo: undefined,
    brand: undefined,
    manufacturer: undefined,
    price: undefined,
    purchasePrice: undefined,
    materialModel: undefined,
    materialType: undefined,
    unitWeight: undefined,
    unitArea: undefined,
    totalArea: undefined,
    totalWeight: undefined,
    thickness: undefined,
    length: undefined,
    breadth: undefined,
    imageUrl: undefined,
    process: undefined,
    mileagePrice: undefined,
    unitPriceCoefficient: undefined,
    materialRequisitionCoefficient: undefined,
    isActive: 0,
    createTime: undefined,
    updateTime: undefined,
    fileList: []
  })
  onClose()
}

// 提交表单
const submit = async () => {


  await addFormRef.value?.validate()
  try {
    if (addForm.id) {
      await updateApi(addForm)
      ElMessage.success('编辑成功')
    } else {
      await addApi(addForm)
      ElMessage.success('新增成功')
    }
    getTableData()
    closeDialog()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// ----------------------- 删除相关 -----------------------
const deleteOne = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除该物料吗？')
  console.error("提示返回：" + confirm)
  if (confirm) {
    try {
      await deleteApi(id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}


// ----------------------- 树形数据处理 -----------------------
// 上级分类选择器的数据
const parentOptions = ref<any[]>([])

/**
 * 获取分类列表数据
 * 用于新增/编辑表单中的物料的分类选择
 */
const getParentCategories = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      // 直接使用处理后的树形数据
      parentOptions.value = handleParentTree(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

/**
 * 处理分类树形数据
 * @param data 原始数据
 * @returns 处理后的树形数据
 */
const handleParentTree = (data: any[]) => {
  const map = new Map()
  const result: any[] = []

  // 初始化映射表
  data.forEach(item => {
    map.set(item.id, {
      id: item.id,
      value: item.id,
      label: item.categoryName,
      children: []
    })
  })

  // 构建树形结构
  data.forEach(item => {
    const node = map.get(item.id)
    if (item.parentId === "0") {
      // 顶级分类直接加入结果数组
      result.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  return result
}


// ----------------------- 左侧筛选树形数据处理 -----------------------
// 当前选中的分类ID，用于树形筛选
const currentCategoryId = ref<number>()

// 定义树节点类型
interface TreeNode {
  id: string;
  categoryName: string;
  parentId: string;
  children: TreeNode[];
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])
/**
 * 获取侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

/**
 * 处理左侧筛选树形结构
 * @param data 原始数据
 * @returns 处理后的树形数据，包含虚拟顶级节点
 */
const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>();
  const result: TreeNode[] = [];

  // 创建虚拟的顶级节点
  const rootNode: TreeNode = {
    id: '-1',
    categoryName: '全部分类',
    parentId: '',
    children: [],
  };

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, {...item, children: []});
  });

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)!;
    if (item.parentId === "0") {
      rootNode.children.push(node);
    } else {
      const parent = map.get(item.parentId);
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  result.push(rootNode);
  return result;
};


/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击
  if (data.id === '-1') {
    currentCategoryId.value = undefined;
    searchForm.categoryId = undefined;
  } else {
    currentCategoryId.value = data.id;
    searchForm.categoryId = data.id;
  }
  // 重置分页和搜索条件
  searchForm.page = 1;
  searchForm.limit = 10;
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.brand = undefined
  searchForm.manufacturer = undefined
  searchForm.materialType = undefined
  searchForm.isActive = undefined
  await getTableData();
}


// ---------------------- 物料单位，用于物料单位下拉框 ----------------------
const unitOptions = ref<Unit[]>([])

// 获取单位数据
const getUnitData = async () => {
  try {
    const res = await getUnitSimpleListApi()
    if (res?.data) {
      unitOptions.value = res.data
    }
  } catch (error) {
    console.error('获取物料单位数据失败:', error)
    ElMessage.error('获取物料单位数据失败')
  }
}
// ----------------------- 文件上传 -----------------------
const handleUploadSuccess = (response: any, file: any) => {
  // 假设后端返回的格式是 { imageUrl: 'xxx' }
  console.log(response);
  addForm.imageUrl = response.data
  addForm.fileList = [file] // 更新文件列表
}

// ----------------------- 图片预览相关 -----------------------
const previewVisible = ref(false)
const previewImageUrl = ref('')
const previewImageTitle = ref('')

// 图片预览处理
const handlePictureCardPreview = (file: any) => {
  // 处理上传组件的图片预览
  if (file) {
    previewImageUrl.value = file.url || ('http://localhost:5173/api' + addForm.imageUrl)
    previewImageTitle.value = file.name || '物料图片'
    previewVisible.value = true
  }
};

// 表格中图片预览
const handleTableImagePreview = (imageUrl: string, title: string) => {
  if (imageUrl) {
    previewImageUrl.value = 'http://localhost:5173/api' + imageUrl
    previewImageTitle.value = title || '物料图片'
    previewVisible.value = true
  }
}

// 关闭预览
const closePreview = () => {
  previewVisible.value = false
}

// 打开原图
const openOriginalImage = () => {
  if (previewImageUrl.value) {
    window.open(previewImageUrl.value)
  }
}

// 图片移除处理
const handleRemove = () => {
  addForm.imageUrl = undefined // 使用undefined而不是null
  addForm.fileList = []
}

const beforeUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }

  return true
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  // 左侧筛选树形数据
  getTreeData()
  // 表格数据
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 分类选择器的数据
  getParentCategories();
  // 物料单位，下拉框数据
  getUnitData();
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="material-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 左侧树形菜单 -->
        <el-col :span="4">
          <el-card class="tree-card" shadow="hover">
            <div class="tree-header">
              <el-icon :size="18"><Folder /></el-icon>
              <span>物料分类</span>
            </div>
            <TreeSelect
              :data="treeData"
              :props="{
                children: 'children',
                label: 'categoryName'
              }"
              placeholder="请输入分类名称"
              @node-click="handleTreeNodeClick"
              class="category-tree"
            />
          </el-card>
        </el-col>
        
        <!-- 右侧内容区 -->
        <el-col :span="20">
          <!-- 查询表单区域 -->
          <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="物料编码">
                <el-input 
                  v-model="searchForm.materialCode" 
                  placeholder="请输入物料编码" 
                  clearable 
                  prefix-icon="Document"
                />
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input 
                  v-model="searchForm.materialName" 
                  placeholder="请输入物料名称" 
                  clearable 
                  prefix-icon="Goods"
                />
              </el-form-item>
              <el-form-item label="品牌">
                <el-input 
                  v-model="searchForm.brand" 
                  placeholder="请输入品牌" 
                  clearable 
                  prefix-icon="ShoppingBag" 
                />
              </el-form-item>
              <el-form-item label="生产厂家">
                <el-input 
                  v-model="searchForm.manufacturer" 
                  placeholder="请输入生产厂家" 
                  clearable 
                  prefix-icon="OfficeBuilding" 
                />
              </el-form-item>
              <el-form-item label="材质">
                <el-input 
                  v-model="searchForm.materialType" 
                  placeholder="请输入材质" 
                  clearable 
                  prefix-icon="Setting" 
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select 
                  v-model="searchForm.isActive" 
                  placeholder="请选择状态" 
                  clearable
                  style="width: 120px"
                >
                  <el-option label="启用" :value="0" />
                  <el-option label="禁用" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary" @click="search" class="search-btn" :icon="Search">
                  查询
                </el-button>
                <el-button @click="reset" class="reset-btn" :icon="Refresh">
                  重置
                </el-button>
                <el-button type="success" @click="openAdd" class="add-btn" :icon="Plus">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card" shadow="hover">
            <el-table
              v-loading="loading"
              :data="tableData"
              border
              :height="tableHeight"
              class="data-table"
              highlight-current-row
            >
              <el-table-column type="index" label="序号" width="70" align="center"/>
              <el-table-column prop="materialCode" label="物料编码" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="materialName" label="物料名称" min-width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="categoryName" label="物料类型" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column label="图片" width="120" align="center">
                <template #default="scope">
                  <el-image
                    v-if="scope.row.imageUrl"
                    style="width: 80px; height: 80px; border-radius: 6px; object-fit: cover; cursor: pointer;"
                    :src="'http://localhost:5173/api' + scope.row.imageUrl"
                    fit="cover"
                    @click="handleTableImagePreview(scope.row.imageUrl, scope.row.materialName)"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div v-else class="no-image">
                    <el-icon><Picture /></el-icon>
                    <span>暂无图片</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="unitName" label="计量单位" min-width="90" align="center" show-overflow-tooltip />
              <el-table-column prop="specification" label="规格" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="price" label="采购价格" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.price">{{ scope.row.price }} 元</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="purchasePrice" label="采购单价" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.purchasePrice">{{ scope.row.purchasePrice }} 元</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="品牌" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="manufacturer" label="生产厂家" min-width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="materialType" label="材质" min-width="100" align="center" show-overflow-tooltip />  
              <el-table-column prop="unitWeight" label="米重(kg/m)" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.unitWeight">{{ scope.row.unitWeight }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="unitArea" label="面积(m²/m)" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.unitArea">{{ scope.row.unitArea }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalArea" label="总面积(m²/件)" min-width="110" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.totalArea">{{ scope.row.totalArea }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalWeight" label="总重(kg/件)" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.totalWeight">{{ scope.row.totalWeight }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="thickness" label="厚度(mm)" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.thickness">{{ scope.row.thickness }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="length" label="高度" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.length">{{ scope.row.length }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="breadth" label="宽度" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.breadth">{{ scope.row.breadth }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="isActive" label="状态" min-width="80" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.isActive === 0 ? 'success' : 'danger'">
                    {{ scope.row.isActive === 0 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary" size="small" :icon="Edit" @click="openEdit(scope.row)" class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="deleteOne(scope.row.id)" class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-model:current-page="paginationData.currentPage"
              v-model:page-size="paginationData.pageSize"
              :page-sizes="[10, 20, 50]"
              :total="paginationData.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="pagination"
              @size-change="getTableData"
              @current-change="getTableData"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
        :title="dialog.title"
        :width="dialog.width"
        :visible="dialog.visible"
        :height="dialog.height"
        @onClose="closeDialog"
        @onConfirm="submit"
        custom-class="material-dialog"
    >
      <template #content>
        <el-scrollbar height="100%" class="form-scrollbar">
          <el-form
              ref="addFormRef"
              :model="addForm"
              :rules="rules"
              label-width="90px"
              class="material-form"
          >
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <el-icon><Document /></el-icon>
                  <span>基本信息</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="物料编码" prop="materialCode">
                    <el-input v-model="addForm.materialCode" placeholder="请输入物料编码" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="物料名称" prop="materialName">
                    <el-input v-model="addForm.materialName" placeholder="请输入物料名称" clearable />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="物料类型" prop="categoryId">
                    <el-tree-select
                        class="full-width"
                        v-model="addForm.categoryId"
                        :data="parentOptions"
                        :render-after-expand="false"
                        show-checkbox
                        check-strictly
                        placeholder="请选择物料类型"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计量单位" prop="unitId">
                    <el-select v-model="addForm.unitId" filterable clearable placeholder="请选择计量单位" class="full-width">
                      <el-option v-for="unit in unitOptions" :key="unit.id" :label="unit.unitName" :value="unit.id">
                        <span style="float: left">{{ unit.unitName }}</span>
                        <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">{{ unit.unitSymbol }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="规格">
                    <el-input v-model="addForm.specification" placeholder="请输入规格" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="规格2">
                    <el-input v-model="addForm.specificationTwo" placeholder="请输入规格2" clearable />
                  </el-form-item>
                </el-col>
        
              </el-row>

              <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料型号">
                    <el-input v-model="addForm.materialModel" placeholder="请输入物料型号" clearable />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工艺">
                    <el-input v-model="addForm.process" placeholder="请输入工艺" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="品牌">
                    <el-input v-model="addForm.brand" placeholder="请输入品牌" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="生产厂家">
                    <el-input v-model="addForm.manufacturer" placeholder="请输入生产厂家" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="采购价格">
                    <el-input-number
                        v-model="addForm.price"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        placeholder="请输入采购价格"
                        class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="采购单价">
                    <el-input-number
                        v-model="addForm.purchasePrice"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        placeholder="请输入采购单价"
                        class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <el-icon><Setting /></el-icon>
                  <span>物料规格参数</span>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="材质">
                    <el-input v-model="addForm.materialType" placeholder="请输入材质" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="米重">
                    <el-input-number
                      v-model="addForm.unitWeight"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入米重(kg/m)"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="米面积">
                    <el-input-number
                      v-model="addForm.unitArea"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入米面积(m²/m)"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总面积">
                    <el-input-number
                      v-model="addForm.totalArea"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入总面积(m²/件)"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="总重">
                    <el-input-number
                      v-model="addForm.totalWeight"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入总重(kg/件)"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="厚度">
                    <el-input-number
                      v-model="addForm.thickness"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入厚度(mm)"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="宽度">
                    <el-input-number
                      v-model="addForm.breadth"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入宽度"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="高度">
                    <el-input-number
                      v-model="addForm.length"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      placeholder="请输入高度"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <el-icon><Grid /></el-icon>
                  <span>成本计算参数</span>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="人工公里数单价">
                    <el-input v-model="addForm.mileagePrice" placeholder="请输入人工公里数单价" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单价索取系数">
                    <el-input v-model="addForm.unitPriceCoefficient" placeholder="请输入单价索取系数" clearable />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="材料索取系数">
                    <el-input v-model="addForm.materialRequisitionCoefficient" placeholder="请输入材料索取系数" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="启用状态">
                    <el-select v-model="addForm.isActive" placeholder="请选择启用状态" class="full-width">
                      <el-option label="启用" :value="0" />
                      <el-option label="禁用" :value="1" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <el-icon><Picture /></el-icon>
                  <span>物料图片</span>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="物料图片">
                    <el-upload
                      action="api/material/upload"
                      list-type="picture-card"
                      :file-list="addForm.fileList"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="handleUploadSuccess"
                      :before-upload="beforeUpload"
                      :limit="1"
                      class="material-upload"
                    >
                      <template #default>
                        <el-icon><Plus /></el-icon>
                        <div class="upload-text">上传图片</div>
                      </template>
                      <template #file="{ file }">
                        <div class="upload-file">
                          <img class="upload-image" :src="file.url" alt="图片预览"/>
                          <div class="upload-actions">
                            <el-icon @click.stop="handlePictureCardPreview(file)"><ZoomIn /></el-icon>
                            <el-icon @click.stop="handleRemove()"><Delete /></el-icon>
                          </div>
                        </div>
                      </template>
                    </el-upload>
                    <div class="upload-tips">
                      <el-icon><InfoFilled /></el-icon>
                      <span>支持jpg/png格式，大小不超过5MB</span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </el-scrollbar>
      </template>
    </sys-dialog>
    
    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="previewImageTitle"
      width="700px"
      class="preview-dialog"
      @close="closePreview"
      destroy-on-close
      append-to-body
    >
      <div class="preview-container">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
      <template #footer>
        <div class="preview-footer">
          <el-button @click="closePreview">关闭</el-button>
          <el-button type="primary" @click="openOriginalImage">查看原图</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.material-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.tree-card {
  border-radius: 8px;
  height: calc(100vh - 100px);
  
  :deep(.el-card__body) {
    padding: 15px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .tree-header {
    padding: 12px 0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #67c23a;
    border-bottom: 1px solid #e1f3d8;
    
    .el-icon {
      margin-right: 8px;
      color: #67c23a;
    }
  }
  
  .category-tree {
    height: calc(100vh - 160px);
    overflow: auto;
    flex: 1;
    
    :deep(.el-tree-node__content) {
      height: 36px;
      
      &:hover {
        background-color: #f0f9eb;
      }
    }
    
    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #e1f3d8;
      color: #67c23a;
    }
  }
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .no-image {
    height: 80px;
    width: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f7f7f7;
    color: #909399;
    font-size: 12px;
    border-radius: 6px;
    gap: 5px;
    
    .el-icon {
      font-size: 22px;
      color: #c0c4cc;
    }
  }
  
  .image-error {
    height: 80px;
    width: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    color: #909399;
    font-size: 12px;
    border-radius: 6px;
    gap: 5px;
    
    .el-icon {
      font-size: 22px;
      color: #c0c4cc;
    }
  }
  
  .no-data {
    color: #c0c4cc;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

// 弹窗样式
:deep(.material-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    
    .el-button {
      padding: 8px 20px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.form-scrollbar {
  max-height: calc(80vh - 120px);
  overflow-y: auto;
}

.material-form {
  padding: 20px;
  
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }
  
  .material-upload {
    :deep(.el-upload--picture-card) {
      width: 140px;
      height: 140px;
      border-radius: 8px;
      background-color: #fafafa;
      border: 1px dashed #d9d9d9;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 10px;
      
      .el-icon {
        font-size: 24px;
        color: #67c23a;
      }
      
      .upload-text {
        font-size: 14px;
        color: #67c23a;
      }
      
      &:hover {
        border-color: #67c23a;
        background-color: #f0f9eb;
      }
    }
    
    :deep(.el-upload-list--picture-card) {
      .el-upload-list__item {
        width: 140px;
        height: 140px;
        border-radius: 8px;
        overflow: hidden;
      }
    }
    
    .upload-file {
      position: relative;
      width: 100%;
      height: 100%;
      
      .upload-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .upload-actions {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        gap: 15px;
        padding: 8px 0;
        
        .el-icon {
          color: #fff;
          font-size: 18px;
          cursor: pointer;
          
          &:hover {
            color: #67c23a;
          }
        }
      }
    }
  }
  
  .upload-tips {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    gap: 5px;
    
    .el-icon {
      color: #f56c6c;
    }
  }

  :deep(.el-input), :deep(.el-select), :deep(.el-tree-select), :deep(.el-input-number) {
    width: 100%;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}

// 图片预览对话框样式
:deep(.preview-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
  }
}

.preview-container {
  width: 100%;
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  overflow: hidden;
  
  .preview-image {
    max-width: 100%;
    max-height: 500px;
    object-fit: contain;
  }
}

.preview-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
